 //
//  MJNetWorking.m
//  Wongo
//
//  Created by rexsu on 2017/2/6.
//  Copyright © 2017年 Wongo. All rights reserved.
//

#import "MJNetWorking.h"

@implementation MJNetWorking

+(AFHTTPSessionManager*)createManagerIsSynchronous:(BOOL)isSynchronous{
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    if (isSynchronous) {
        manager.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    }
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //设置超时时间10秒
    manager.requestSerializer.timeoutInterval = 10.f;
    //app应用相关信息的获取
    NSDictionary *dicInfo = [[NSBundle mainBundle] infoDictionary];
    //App版本
    NSString *strAppVersion = [dicInfo objectForKey:@"CFBundleShortVersionString"];
    //系统名称
    NSString *strSysName =[[UIDevice currentDevice]systemName];
    //系统版本
    NSString *strSysVersion = [[UIDevice currentDevice]systemVersion];
    //设备模式
    NSString *strModel=[[UIDevice currentDevice]model];
    //设备本地模式
    NSString *strLocModel =[[UIDevice currentDevice]localizedModel];
    //设备的平台
    [manager.requestSerializer setValue:strSysName forHTTPHeaderField:@"platform"];
    //设备的型号(模式)
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"model:%@\t locModel:%@",strModel,strLocModel] forHTTPHeaderField:@"type"];
    //系统版本
    [manager.requestSerializer setValue:strSysVersion forHTTPHeaderField:@"sysVersion"];
    //App的版本
    [manager.requestSerializer setValue:strAppVersion forHTTPHeaderField:@"appVersion"];
    //
    [manager.requestSerializer setValue:UserManager.shared.userToken forHTTPHeaderField:@"token"];
    
    [manager.requestSerializer setValue:LanguageHelper.shared.httpLanguage forHTTPHeaderField:@"Accept-Language"];
    //
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json", @"text/javascript", @"text/plain", nil];
    return manager;
}

#pragma mark -
+(RACSignal *)createDeleteRequestMenagerWithHttpRequest:(MJHttpRequest *)request{
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        AFHTTPSessionManager * manager =  [MJNetWorking createManagerIsSynchronous:NO];
        [manager DELETE:request.requestApi parameters:request.param headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

            NSDictionary * dic = [((NSData *)responseObject) mj_toDistionary];
            if (request.responseObject == nil) {
                [subscriber sendNext:dic];
            }else
                [subscriber sendNext:[request.responseObject yy_modelWithDictionary:dic]];
            [subscriber sendCompleted];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

            [subscriber sendError:error];
        }];
        return nil;
    }];
}

+(RACSignal *)createPutRequestMenagerWithHttpRequest:(MJHttpRequest *)request{

    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        AFHTTPSessionManager * manager =  [MJNetWorking createManagerIsSynchronous:NO];
        [manager PUT:request.requestApi parameters:request.param headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

            NSDictionary * dic = [((NSData *)responseObject) mj_toDistionary];
            if (request.responseObject == nil) {
                [subscriber sendNext:dic];
            }else
                [subscriber sendNext:[request.responseObject yy_modelWithDictionary:dic]];
            [subscriber sendCompleted];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [subscriber sendError:error];
        }];
        return nil;
    }];
}

+(RACSignal *)createGetRequestMenagerWithHttpRequest:(MJHttpRequest *)request{

    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        AFHTTPSessionManager * manager =  [MJNetWorking createManagerIsSynchronous:NO];
        [manager GET:request.requestApi parameters:request.param headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary * dic = [((NSData *)responseObject) mj_toDistionary];
            if (request.responseObject == nil) {
                [subscriber sendNext:dic];
            }else
                [subscriber sendNext:[request.responseObject yy_modelWithDictionary:dic]];
            [subscriber sendCompleted];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [subscriber sendError:error];
        }];
        return nil;
    }];
}

+(RACSignal *)createPostBodyRequestMenagerWithHttpRequest:(MJHttpRequest *)request{

    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        AFHTTPSessionManager * manager =  [self createManagerIsSynchronous:NO];
        NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:request.requestApi parameters:nil error:nil];
        [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [req setValue:UserManager.shared.userToken forHTTPHeaderField:@"token"];
        [req setValue:LanguageHelper.shared.httpLanguage forHTTPHeaderField:@"Accept-Language"];
        // 关键! 转化为NSaData作为HTTPBody
        [req setHTTPBody:[MJUIEmptyDictionary(request.param) ? @"" : [request.param mj_dictionaryConvertToString] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [[manager dataTaskWithRequest:req uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            if (!error) {
                NSDictionary * dic = [((NSData *)responseObject) mj_toDistionary];
                if (request.responseObject == nil)
                    [subscriber sendNext:dic];
                else
                    [subscriber sendNext:[request.responseObject yy_modelWithDictionary:dic]];
                [subscriber sendCompleted];
            }
            else{
                [subscriber sendError:error];
            }
            
        }] resume];
        return nil;
    }];
}

+(RACSignal *)createPutBodyRequestMenagerWithHttpRequest:(MJHttpRequest *)request{
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        AFHTTPSessionManager * manager =  [self createManagerIsSynchronous:NO];
        NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"PUT" URLString:request.requestApi parameters:nil error:nil];
        [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [req setValue:UserManager.shared.userToken forHTTPHeaderField:@"token"];
        [req setValue:LanguageHelper.shared.httpLanguage forHTTPHeaderField:@"Accept-Language"];

        // 关键! 转化为NSaData作为HTTPBody
        [req setHTTPBody:[MJUIEmptyDictionary(request.param) ? @"" : [request.param mj_dictionaryConvertToString] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [[manager dataTaskWithRequest:req uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            if (!error) {
                NSDictionary * dic = [((NSData *)responseObject) mj_toDistionary];
                if (request.responseObject == nil)
                    [subscriber sendNext:dic];
                else
                    [subscriber sendNext:[request.responseObject yy_modelWithDictionary:dic]];
                [subscriber sendCompleted];
            }
            else{
                [subscriber sendError:error];
            }
            
        }] resume];
        return nil;
    }];
}

@end
